using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NTTHAO.Web.BL.CommonPage;
using NTTHAO.CommonWeb;
using System.IO;
using NTTHAO.Imaging;

public partial class admin_webparts_Plug_ins_CommonPage_CommonImageInput : System.Web.UI.UserControl
{
    public CommonAlbum _Album = null;
    public CommonImage _Detail = null;
    public string _ErrorMessage = String.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        this.btnSave.Text = this.btnSave2.Text = LanguageUtility.GetLanguageText("SAVE", Session);
        this.chkActive1.Text 
            = this.chkActive2.Text
            = this.chkActive3.Text
            = this.chkActive4.Text
            = this.chkActive5.Text
            = this.chkActive6.Text
            = this.chkActive7.Text
            = this.chkActive8.Text
            = this.chkActive9.Text
            = this.chkActive10.Text 
            = LanguageUtility.GetLanguageText("ACTIVE", Session);

        if (!IsPostBack)
        {
            //this.chkResizeImage.Checked = false;
            try
            {
                int albumID = Int32.Parse(Request.QueryString["albumid"]);
                CommonAlbum album = new CommonAlbum(albumID);
                if (album.ID > 0)
                {
                    _Album = album;

                    this.txtResizeImageWidth.Text = _Album.DefaultWidth.ToString();
                    this.txtResizeImageHeight.Text = _Album.DefaultHeight.ToString();

                    if ("editimage".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
                    {
                        CommonImage detail = new CommonImage(Int32.Parse(Request.QueryString["id"]));
                        if (detail.ID > 0 && detail.AlbumID == album.ID)
                        {
                            this._Detail = detail;
                            this.txtImageName1.Text = detail.ImageName;
                            this.txtURL1.Text = detail.LinkURL.Replace("http://", "");
                            this.chkActive1.Checked = detail.Active;
                        }
                        else
                        {
                            Response.Redirect("CommonPageContent.aspx?action=invalidurl", false);
                            return;
                        }
                    }
                }
                else
                {
                    Response.Redirect("CommonPageContent.aspx?action=invalidurl", false);
                    return;
                }
            }
            catch (Exception)
            {
            }
        }

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            int albumID = Int32.Parse(Request.QueryString["albumid"]);
            CommonAlbum album = new CommonAlbum(albumID);
            if (album.ID > 0)
            {
                bool resizeAll = chkResizeImage.Checked;
                int maxWidth = album.DefaultWidth;
                int maxHeight = album.DefaultHeight;
                Int32.TryParse(txtResizeImageWidth.Text.Trim(), out maxWidth);
                Int32.TryParse(txtResizeImageHeight.Text.Trim(), out maxHeight);

                if ("editimage".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
                {
                    CommonImage detail = new CommonImage(Int32.Parse(Request.QueryString["id"]));
                    if (detail.ID > 0 && detail.AlbumID == album.ID)
                    {
                        this.UpdateImage(album, detail, txtImageName1.Text.Trim(), fuImage1, txtURL1.Text.Trim(), chkActive1.Checked, resizeAll, maxWidth, maxHeight);
                    }
                }
                else
                {
                    this.InsertImage(album, txtImageName1.Text.Trim(), fuImage1, txtURL1.Text.Trim(), chkActive1.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName2.Text.Trim(), fuImage2, txtURL2.Text.Trim(), chkActive2.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName3.Text.Trim(), fuImage3, txtURL3.Text.Trim(), chkActive3.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName4.Text.Trim(), fuImage4, txtURL4.Text.Trim(), chkActive4.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName5.Text.Trim(), fuImage5, txtURL5.Text.Trim(), chkActive5.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName6.Text.Trim(), fuImage6, txtURL6.Text.Trim(), chkActive6.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName7.Text.Trim(), fuImage7, txtURL7.Text.Trim(), chkActive7.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName8.Text.Trim(), fuImage8, txtURL8.Text.Trim(), chkActive8.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName9.Text.Trim(), fuImage9, txtURL9.Text.Trim(), chkActive9.Checked, resizeAll, maxWidth, maxHeight);
                    this.InsertImage(album, txtImageName10.Text.Trim(), fuImage10, txtURL10.Text.Trim(), chkActive10.Checked, resizeAll, maxWidth, maxHeight);
                }
            }

            Response.Redirect("CommonPageContent.aspx?action=viewalbum&g=" + Request.QueryString["g"] + "&mnuid=" + Request.QueryString["mnuid"] + "&id=" + Request.QueryString["albumid"] + "&time=" + DateTime.Now.Ticks.ToString(), false);
            return;
        }
        catch (Exception ex)
        {
            this._ErrorMessage = ex.Message + (ex.StackTrace == null ? "" : (Environment.NewLine + ex.StackTrace));
        }
    }

    protected void InsertImage(CommonAlbum album, string title, FileUpload uploader, string url, bool actived,
        bool resizeImage,
        int maxWidth,
        int maxHeight)
    {
        if (album == null || album.ID < 1 || !uploader.HasFile)
        {
            return;
        }

        CommonImage image = new CommonImage();
        image.AlbumID = album.ID;
        image.ImageName = title;
        image.LinkURL = url.Trim().Length < 1 ? "#" : url.Trim();
        image.Active = actived;
        image.ImageFileName = "";
        image.Insert();

        image.ImageFileName = this.SavePostedFile(album, image, uploader, resizeImage, maxWidth, maxHeight);
        image.Update();
        /*
        string imageFilePath = album.ImagePath; // "resources/uploaded/commonpage/album/" + album.ID.ToString() + "/";
        string serverFilePath = Server.MapPath("../" + imageFilePath);
        if (!Directory.Exists(serverFilePath))
        {
            Directory.CreateDirectory(serverFilePath);
        }
        string imageFileName = "Img_" + image.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(uploader.PostedFile.FileName);
        string serverFileName = Path.Combine(serverFilePath, imageFileName);
        if (System.IO.File.Exists(serverFileName))
        {
            System.IO.File.Delete(serverFileName);
        }
        uploader.PostedFile.SaveAs(serverFileName);

        image.ImageFileName = imageFileName;
        image.Update();

        string miniFilePath = Path.Combine(serverFilePath, "Mini_" + imageFileName);
        if (System.IO.File.Exists(miniFilePath))
        {
            System.IO.File.Delete(miniFilePath);
        }
        System.IO.File.Copy(serverFileName, miniFilePath);
        Common.ResizeImage(miniFilePath, album.MiniDefaultWidth, album.MiniDefaultHeight);
        */

    }

    protected void UpdateImage(CommonAlbum album, 
        CommonImage image, 
        string title, 
        FileUpload uploader, 
        string url, 
        bool actived,
        bool resizeImage,
        int maxWidth,
        int maxHeight)
    {
        if (album == null || album.ID < 1 
            || image == null || image.ID < 1)
        {
            return;
        }

        image.AlbumID = album.ID;
        image.ImageName = title;
        image.LinkURL = url.Trim().Length < 1 ? "#" : url.Trim();
        image.Active = actived;

        if (uploader.HasFile)
        {
            string imageFilePath = album.ImagePath; // "resources/uploaded/commonpage/album/" + album.ID.ToString() + "/";
            string serverFilePath = Server.MapPath("../" + imageFilePath);

            if (File.Exists(Path.Combine(serverFilePath, image.ImageFileName)))
            {
                File.Delete(Path.Combine(serverFilePath, image.ImageFileName));
            }
            if (File.Exists(Path.Combine(serverFilePath, "Mini_" + image.ImageFileName)))
            {
                File.Delete(Path.Combine(serverFilePath, "Mini_" + image.ImageFileName));
            }
            image.ImageFileName = this.SavePostedFile(album, image, uploader, resizeImage, maxWidth, maxHeight);
            /*
            if (!Directory.Exists(serverFilePath))
            {
                Directory.CreateDirectory(serverFilePath);
            }
            string imageFileName = "Img_" + image.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(uploader.PostedFile.FileName);
            string serverFileName = Path.Combine(serverFilePath, imageFileName);
            if (System.IO.File.Exists(serverFileName))
            {
                System.IO.File.Delete(serverFileName);
            }
            uploader.PostedFile.SaveAs(serverFileName);

            image.ImageFileName = imageFileName;

            string miniFilePath = Path.Combine(serverFilePath, "Mini_" + imageFileName);
            if (File.Exists(miniFilePath))
            {
                File.Delete(miniFilePath);
            }
            System.IO.File.Copy(serverFileName, miniFilePath);
            Common.ResizeImage(miniFilePath, album.MiniDefaultWidth, album.MiniDefaultHeight);
            */
        }

        image.Update();
    }

    public string SavePostedFile(CommonAlbum album, CommonImage image, FileUpload uploader,
        bool resizeImage,
        int maxWidth,
        int maxHeight)
    {
        string imageFilePath = album.ImagePath;
        string serverFilePath = Server.MapPath("../" + imageFilePath);

        if (image.ImageFileName.Length > 0)
        {
            if (File.Exists(Path.Combine(serverFilePath, image.ImageFileName)))
            {
                File.Delete(Path.Combine(serverFilePath, image.ImageFileName));
            }
            if (File.Exists(Path.Combine(serverFilePath, "Mini_" + image.ImageFileName)))
            {
                File.Delete(Path.Combine(serverFilePath, "Mini_" + image.ImageFileName));
            }
            if (File.Exists(Path.Combine(serverFilePath, "Mini_" + Path.ChangeExtension(image.ImageFileName, ".jpg"))))
            {
                File.Delete(Path.Combine(serverFilePath, "Mini_" + Path.ChangeExtension(image.ImageFileName, ".jpg")));
            }
        }

        if (!Directory.Exists(serverFilePath))
        {
            Directory.CreateDirectory(serverFilePath);
        }
        string imageFileName = album.URLName + "_img_" + image.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(uploader.PostedFile.FileName);
        string serverFileName = Path.Combine(serverFilePath, imageFileName);
        if (File.Exists(serverFileName))
        {
            File.Delete(serverFileName);
        }
        uploader.PostedFile.SaveAs(serverFileName);

        if (resizeImage || Constant.ADD_LAYER_MASK)
        {
            imageFileName = Path.GetFileName(ImageUtilities.CompressImageToJpeg(serverFileName, ImageUtilities.HIGHT_PROGRESSIVE));
            serverFileName = Path.ChangeExtension(serverFileName, Path.GetExtension(imageFileName));
        }

        if (resizeImage)
        {
            imageFileName = Path.GetFileName(ImageUtilities.ResizeImageToJpeg(serverFileName, maxWidth, maxHeight, ResizeOptions.MaximumSizeFix, System.Drawing.Color.White, ImageUtilities.HIGHT_PROGRESSIVE));
        }

        //layer mask
        if (Constant.ADD_LAYER_MASK)
        {
            float left = 0, top = 0, width = 0, height = 0, opacity = 1;
            float.TryParse(ConfigValues.GetConfigValue("MASK_TOP_PERCENT").Trim(), out top);
            float.TryParse(ConfigValues.GetConfigValue("MASK_LEFT_PERCENT").Trim(), out left);
            float.TryParse(ConfigValues.GetConfigValue("MASK_WIDTH_PERCENT").Trim(), out width);
            float.TryParse(ConfigValues.GetConfigValue("MASK_HEIGHT_PERCENT").Trim(), out height);
            float.TryParse(ConfigValues.GetConfigValue("MASK_OPACITY").Trim(), out opacity);

            ImageUtilities.DrawLayerMask(serverFileName, Server.MapPath("../" + Constant.MASK_IMAGE_FILE), top, left, width, height, ResizeOptions.MaximumSizeFix, opacity, ImageUtilities.HIGHT_PROGRESSIVE);
        }
        // end

        string miniFilePath = Path.Combine(serverFilePath, "Mini_" + imageFileName);
        if (File.Exists(miniFilePath))
        {
            File.Delete(miniFilePath);
        }
        File.Copy(serverFileName, miniFilePath);

        miniFilePath = ImageUtilities.CompressImageToJpeg(miniFilePath, album.MiniDefaultWidth, album.MiniDefaultHeight, ImageUtilities.HIGHT_PROGRESSIVE);
        //ImageUtilities.MaximumSizeFit(miniFilePath, album.MiniDefaultWidth, album.MiniDefaultHeight, ImageUtilities.HIGHT_PROGRESSIVE);
        //Common.ResizeImage(miniFilePath, album.MiniDefaultWidth, album.MiniDefaultHeight);

        return imageFileName;
    }
}
